//
// Path_UNIX.cpp
//
// $Id: //poco/1.4/Foundation/src/Path_UNIX.cpp#3 $
//
// Library: Foundation
// Package: Filesystem
// Module:  Path
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier:	BSL-1.0
//


#include "Poco/Path.h"
#include "Poco/Exception.h"
#include "Poco/Environment.h"
#include "Poco/File.h"
#include <cctype>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <climits>
#include <pwd.h>

#ifndef PATH_MAX
#define PATH_MAX 1024 // fallback
#endif


namespace Poco {
Path& Path::assign(const std::string& path)
{
    parseUnix(path);
    return *this;
}    

    
std::string Path::toString() const
{
    return buildUnix();
} 
    
    
Path& Path::makeDirectory()
{
    pushDirectory(m_name);
    m_name.clear();
    m_version.clear();
    return *this;
}
    
    
Path& Path::pushDirectory(const std::string& dir)
{
    if (!dir.empty() && dir != ".")
    {
        if (dir == "..")
        {
            if (!m_dirs.empty() && m_dirs.back() != "..")
                m_dirs.pop_back();
            else if (!m_absolute)
                m_dirs.push_back(dir);
        }
        else m_dirs.push_back(dir);
    }
    return *this;
}


bool Path::find(StringVec::const_iterator it, StringVec::const_iterator end, const std::string& name, Path& path)
{
    while (it != end)
    {

        Path p(*it);
        p.makeDirectory();
        p.resolve(Path(name));
        File f(p);
        if (f.exists())
        {
            path = p;
            return true;
        }
        ++it;
    }
    return false;
}

std::string Path::current()
{
	std::string path;
	char cwd[PATH_MAX];
	if (getcwd(cwd, sizeof(cwd)))
		path = cwd;
	else
		throw SystemException("cannot get current directory");
	std::string::size_type n = path.size();
	if (n > 0 && path[n - 1] != '/') path.append("/");
	return path;
}


std::string Path::home()
{
	std::string path;
	struct passwd* pwd = getpwuid(getuid());
	if (pwd)
		path = pwd->pw_dir;
	else
	{
		pwd = getpwuid(geteuid());
		if (pwd)
			path = pwd->pw_dir;
		else
			path = Environment::get("HOME");
	}
	std::string::size_type n = path.size();
	if (n > 0 && path[n - 1] != '/') path.append("/");
	return path;
}


std::string Path::temp()
{
	std::string path;
	char* tmp = getenv("TMPDIR");
	if (tmp)
	{
		path = tmp;
		std::string::size_type n = path.size();
		if (n > 0 && path[n - 1] != '/') path.append("/");
	}
	else
	{
		path = "/tmp/";
	}
	return path;
}


std::string Path::null()
{
	return "/dev/null";
}


std::string Path::expand(const std::string& path)
{
	std::string result;
	std::string::const_iterator it  = path.begin();
	std::string::const_iterator end = path.end();
	if (it != end && *it == '~')
	{
		++it;
		if (it != end && *it == '/')
		{
			result += home(); ++it;
		}
		else result += '~';
	}
	while (it != end)
	{
		if (*it == '$')
		{
			std::string var;
			++it;
			if (it != end && *it == '{')
			{
				++it;
				while (it != end && *it != '}') var += *it++;
				if (it != end) ++it;
			}
			else
			{
				while (it != end && (isalpha(*it) || isdigit(*it) || *it == '_')) var += *it++;
			}
			char* val = getenv(var.c_str());
			if (val) result += val;
		}
		else result += *it++;
	}
	return result;
}


void Path::listRoots(std::vector<std::string>& roots)
{
	roots.clear();
	roots.push_back("/");
}


} // namespace Poco
